package com.jiechuang.gateway.filter;

import com.jiechuang.gateway.util.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.List;


@Component
@Slf4j
public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
	@Autowired
	private JWTUtil jwtUtil;
	private static final String AUTHORIZATION_TOKEN = "Authorization";

	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			String authorization = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION_TOKEN);
			if (StringUtils.hasLength(authorization)) {
				//对令牌认证
				try {
					Claims claims = jwtUtil.parseJWT(authorization);
					List<String> roleCodes = (List<String>) claims.get("roleCodes");
					String username = claims.getSubject();
					return chain.filter(exchange);
				}catch (io.jsonwebtoken.ExpiredJwtException e){
					e.printStackTrace();
					throw new RuntimeException("令牌有效期已到(gateway拦截)，请重新登录");
				}
				catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException("令牌不正确，请重新登录");
				}
			}
			log.error("验证不通过,请重新登录");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
		};
	}
}
